import 'package:flutter_enjoy_plus/constants/index.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Tokenmanager{
  String _token = ''; // 定义一个token变量
  String _refreshToken = ''; // 定义刷新token 变量
  // 获取存储实例
  Future<SharedPreferences> _getInstance() {
    return SharedPreferences.getInstance();
  }

  // 初始化首选项实例
  init() async {
    final instance = await _getInstance();
    _token = instance.getString(GlobalVariable.ENJOY_TOKEN) ?? '';
    _refreshToken = instance.getString(GlobalVariable.REFRESH_TOKEN_KEY) ?? '';
  }

  // 存储token
  setToken(String token,{String? refresh_token}) async {
    // 获取首选项实例
    final instance = await _getInstance();
    // 基于实例 存储
    instance.setString(GlobalVariable.ENJOY_TOKEN, token);
    // 更新token
    _token = token;
    if(refresh_token!=null){
      instance.setString(GlobalVariable.REFRESH_TOKEN_KEY, refresh_token);
      _refreshToken = refresh_token;
    }
  }

  // 获取token
  // getToken() async {
  //   final instance = await _getInstance();
  //   return instance.getString(GlobalVariable.ENJOY_TOKEN);
  // }
  getToken(){
    return _token?? '';  
  }
  String getRefreshToken(){
    return _refreshToken?? '';
  } 

  // 删除token 
  deleteToken() async{
    final instance = await _getInstance();
    instance.remove(GlobalVariable.ENJOY_TOKEN);
    _token = '';
    _refreshToken = '';
    instance.remove(GlobalVariable.REFRESH_TOKEN_KEY);
  }
}
var tokenmanager = Tokenmanager();